<?php

class Bot_IndexController extends Zend_Controller_Action
{

    public function init()
    {
        Zend_Registry::get('layout')->setLayout('duty');
        
        $activeResource=Bot_Model_Bot::RESOURCE_NAME;
        
        // seting active resource
        Zend_Registry::set('resource',$activeResource);

        $this->_flashMessenger = $this->_helper->getHelper('FlashMessenger');
        $this->view->flash_messages = $this->_flashMessenger->getMessages();
    }

    public function indexAction()
    {
        $resource=(string) $this->_getParam('resource');
        
        if (!Zend_Registry::get('user')->canManage() || empty($resource))
        {
            return $this->_response->setRedirect(Zend_Registry::get('view')->fixUrl());
        }
        
        $title='';
        $teaser='';
        $content='';
        
        $bot=new Bot_Model_Bot($resource);
        
        $result=$bot->fetch();
        
        if (empty($result))
        {
            $title=Zend_Registry::get('locale')->_('Empty response');
        } else
        {
            $bot->alterContent($result);
            $bot->doReplace($result);
            
            $keywords=$bot->getKeywords($result);
            $title=$bot->getTitle($result);
            $teaser=$bot->getTeaser($result);
            $content=$bot->getContent($result);
            
            if (empty($result) || empty($title) || empty($teaser) || empty($content))
            {
                $title=Zend_Registry::get('locale')->_('Content pattern did not match');
            } else
            {
                $bot->stripTags($keywords);
                $bot->stripTags($title);
                $bot->stripTags($teaser,'format');
                $bot->stripTags($content,'content');
                
                $bot->replaceImages($content);
                
                $bot->addLink($content);
            
                $bot->saveNode($keywords,$title,$teaser,$content);
            }
        }
        
        $this->view->resource=$resource;
        $this->view->title=$title;
        $this->view->teaser=$teaser;
        $this->view->content=$content;
    }


}

